import React, { useState, useEffect } from "react";
import { useLocation } from "react-router-dom";
import { Space, Avatar, Button, message } from "antd";
import { useSelector } from "react-redux";
import { RootState } from "@/store";
import { userFollowAuthor, userUnFollowAuthor } from "@/apis/userApi.ts";
import { userGetAuthorInfo } from "@/apis/userApi";
import { UserOutlined } from "@ant-design/icons";
import AuthorArticleList from "./AuthorArticleList";
import { AuthorInfo, Article } from "@/apis/shared";
import { removeQuotes, formatDate } from "@/utils/tool";

const Author: React.FC = () => {
  const location = useLocation();

  const [authorInfo, setAuthorInfo] = useState<AuthorInfo<Article>>();
  const parmas = new URLSearchParams(location.search);
  const [userIsFollowed, setUserIsFollowed] = useState(false);
  const [authorArticleList, setAuthorArticleList] = useState<Article[]>([]);
  // 获取当前用户的email
  const userEmail = useSelector(
    (state: RootState) => state.UserInfoStore.email
  );

  // 封装一个函数，用于传递给子组件，做一下兼容处理
  const updateData = (updater: (prevData: Article[]) => Article[]) => {
    setAuthorArticleList(updater);
  };

  // 获取作者的 头像
  const authorAvatar = useSelector(
    (state: RootState) => state.UserInfoStore.authorAvatar
  );

  // 获取作者的email
  const authorEmail = parmas.get("authorEmail");

  const fetchAuthorInfo = async () => {
    // 获取作者信息
    const res = await userGetAuthorInfo(authorEmail!);

    // 设置作者信息
    if (res.code === 200) {
      setAuthorInfo(res.data);
      setAuthorArticleList(res.data?.articleList!);
      setUserIsFollowed(res.data?.fansList.some((item) => item === userEmail)!);
    }
  };

  useEffect(() => {
    fetchAuthorInfo();
  }, []);

  // 用户关注作者
  const handleFollowAuthor = async () => {
    const res = await userFollowAuthor(authorEmail!);

    if (res.code === 200) {
      message.success("关注成功");
      setUserIsFollowed(true);
    } else {
      message.error("关注失败");
    }
  };

  // 用户取消关注
  const handleUnFollowAuthor = async () => {
    const res = await userUnFollowAuthor(authorEmail!);

    if (res.code === 200) {
      message.success("取消关注成功");
      setUserIsFollowed(false);
    } else {
      message.error("取消关注失败");
    }
  };

  console.log("authorEmail", authorEmail);
  return (
    <div style={{ maxWidth: "1000px", margin: "0 auto" }}>
      <Space direction="vertical" style={{ width: "100%" }}>
        <Space direction="horizontal">
          <Space>
            <Avatar
              src={removeQuotes(authorAvatar)}
              size={64}
              icon={<UserOutlined />}
            />
          </Space>
          <Space direction="vertical">
            <div>作者昵称: {authorInfo?.nickname}</div>
            <div>作者email: {authorInfo?.email}</div>
            <div>加入时间：{formatDate(authorInfo?.create_time!)}</div>
          </Space>
          <Space>
            {userIsFollowed ? (
              <Button onClick={handleUnFollowAuthor}>取消关注</Button>
            ) : (
              <Button onClick={handleFollowAuthor} type="primary">
                关注
              </Button>
            )}
          </Space>
        </Space>
        <h3 style={{ textAlign: "center" }}>作者文章列表</h3>
        <div
          style={{
            width: "95%",
            maxWidth: "1000px",
            margin: "0 auto",
          }}
        >
          <AuthorArticleList
            authorArticleList={authorArticleList ? authorArticleList : []}
            setData={updateData}
          />
        </div>
      </Space>
    </div>
  );
};

export default Author;
